package com.flyox.game.militarychess.client.view;

import java.awt.Color;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flyox.game.militarychess.CONSTS;
import com.flyox.game.militarychess.bean.ChessMan;
import com.flyox.game.militarychess.bean.Position;
import com.flyox.game.militarychess.bean.ChessMan.NAME;
import com.flyox.game.militarychess.client.services.DataService;
import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.message.Request;
import com.flyox.game.militarychess.service.ChessService;
import com.flyox.game.militarychess.service.CommonLayoutService;
import com.flyox.game.militarychess.util.Secret;
import com.flyox.game.militarychess.util.SerialUtil;

public class ChessManPanel extends javax.swing.JPanel implements MouseListener {

	private static final long serialVersionUID = -780421835683866040L;
	private final Logger logger = LoggerFactory.getLogger(getClass());
	Image chessManImage;
	public JLabel jLabelChess;
	public ChessMan cm;
	DeskLayoutJPanel parent;
	CommonLayoutService commonLayoutService=new CommonLayoutService();
	private final int[][] ps=commonLayoutService.getPosProperties();
	DataService dataService=new DataService();
	ChessService chessService=new ChessService();
	public ChessManPanel(DeskLayoutJPanel parent,ChessMan cm) {
		super();
		this.cm = cm;
		this.parent=parent;
		initGUI();
	}
	
	/**
	 * 剪裁图片得到x坐标
	 * @return
	 */
	private int getPos(){
		if(cm==null)
			return 0;
		if(cm.getName().equals(NAME.JUNZHANG)){
			return 36;
		}else if(cm.getName().equals(NAME.SHIZHANG)){
			return 72;
		}else if(cm.getName().equals(NAME.LVZHANG)){
			return 108;
		}else if(cm.getName().equals(NAME.TUANZHANG)){
			return 144;
		}else if(cm.getName().equals(NAME.YINGZHANG)){
			return 180;
		}else if(cm.getName().equals(NAME.LIANZHANG)){
			return 216;
		}else if(cm.getName().equals(NAME.PAIZHANG)){
			return 252;
		}else if(cm.getName().equals(NAME.GONGBING)){
			return 288;
		}else if(cm.getName().equals(NAME.JUNQI)){
			return 324;
		}else if(cm.getName().equals(NAME.SILING)){
			return 360;
		}else if(cm.getName().equals(NAME.DILEI)){
			return 396;
		}else if(cm.getName().equals(NAME.ZHANGDAN)){
			return 432;
		}else if(cm.getName().equals(NAME.EMPTY)){
			return 0;
		}else if(cm.getName().equals(NAME.UNKNOW)){
			return 0;
		}
		return 0;
	}
	
	private void initGUI() {
		parent.parent.getQiZiImage(cm.getTeam());
		int x=getPos();
		chessManImage=parent.parent.getQiZiImage(cm.getTeam()).getSubimage(x, 0, 36, 27);
		try {
			this.setPreferredSize(new java.awt.Dimension(36, 27));
			this.setLayout(null);
			{
				jLabelChess = new JLabel();
				this.add(jLabelChess);
				jLabelChess.setIcon(new ImageIcon(chessManImage));
				jLabelChess.setBounds(0, 0, 36, 27);
				jLabelChess.addMouseListener(this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	public void paint(Graphics g) {
//		g.drawImage(chessManImage, 2, 2, this);
//	}

//	public void update(Graphics g) {
//			paint(g);
//	}
	
	public void mouseClicked(MouseEvent e) {
		if(parent.selectedChessManPanel!=null){
			System.out.println("first:"+parent.selectedChessManPanel.cm.getName()+" second:"+cm.getName());
		}else{
			System.out.println("first:"+cm.getName());
		}
		if(dataService.getPlayer().getStates()==CONSTS.PLAYER_STATS_ONSEAT){//调整布局
			//调整布局不可以调整其他人的棋子
			if(!cm.getTeam().equals(dataService.getPlayer().getSeatName())){
				return ;
			}else if(parent.selectedChessManPanel==null){
				jLabelChess.setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.GREEN, 2, true), null));
				parent.parent.updateSysMessage("调整布局。选中第一个棋子，等待第二个");
				parent.selectedChessManPanel=this;
			}else{
				//判断重复点击
				if(cm.getPosition().equals(parent.selectedChessManPanel.cm.getPosition())){
					jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));//消除边框
					parent.selectedChessManPanel=null;
				}else if(chessService.canChangePos(parent.selectedChessManPanel.cm,cm)){//判断是否可以交换位置
					logger.trace("client change pos first:"+parent.selectedChessManPanel.cm.getName()+" second:"+cm.getName());
					//交换控件位置
					Rectangle rg=this.getBounds();
					this.setBounds(parent.selectedChessManPanel.getBounds());
					parent.selectedChessManPanel.setBounds(rg);
					//交换棋子坐标
					Position p=cm.getPosition();
					cm.setPosition(parent.selectedChessManPanel.cm.getPosition());
					parent.selectedChessManPanel.cm.setPosition(p);
					//修改布局
					ChessMan[][] cms=dataService.getLayout();
					ChessMan tcm=cms[cm.getPosition().row][cm.getPosition().col];
					cms[cm.getPosition().row][cm.getPosition().col]=cms[parent.selectedChessManPanel.cm.getPosition().row][parent.selectedChessManPanel.cm.getPosition().col];
					cms[parent.selectedChessManPanel.cm.getPosition().row][parent.selectedChessManPanel.cm.getPosition().col]=tcm;
					//清空状态
					parent.parent.updateSysMessage("调整布局。选中第二个棋子。");
					parent.selectedChessManPanel.jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
					parent.selectedChessManPanel=null;
				}else{
					//不可以交换位置
				}
			}
		}else if(dataService.getPlayer().getStates()==CONSTS.PLAYER_STATS_PLAYING){//走棋 点的是空位置不会走到这里 其他地方判断是否无棋可走
			//没有轮到走棋不可以走棋
			if(!dataService.getChessDesk().getOnTurn().equals(dataService.getPlayer().getSeatName())){
				return ;
			}else if(parent.selectedChessManPanel==null){
				if(!cm.getTeam().equals(dataService.getPlayer().getSeatName())){//第一次不可以选其他人的棋子
					return ;
				}
				//地雷 军旗不可以选
				if(cm.getName().equals(NAME.DILEI)||cm.getName().equals(NAME.JUNQI)){
					return ;
				}
				// 大本营（第一步选子阶段）不可以选
				if((ps[cm.getPosition().row][cm.getPosition().col]&CONSTS.POS_SUPREME_HEADQUARTER)!=0){
					return ;
				}
				parent.parent.updateSysMessage("走棋。选中第一个棋子，等待第二个");
				jLabelChess.setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.GREEN, 2, true), null));
				parent.selectedChessManPanel=this;
			}else if(cm.getPosition().equals(parent.selectedChessManPanel.cm.getPosition())){//判断重复点击
				parent.selectedChessManPanel=null;
				jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
			}else if(cm.getTeam().equals(dataService.getPlayer().getSeatName())){//选中自己的棋子
				parent.selectedChessManPanel.jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
				parent.selectedChessManPanel=this;
				jLabelChess.setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.GREEN, 2, true), null));
			}else if(chessService.sameTeamChessMan(parent.selectedChessManPanel.cm.getTeam(),cm.getTeam())){
				//第二次不可以选同伙或者自己棋子
				return ;
			}else if(chessService.canMoveHere(dataService.getLayout(),parent.selectedChessManPanel.cm,cm.getPosition())){//可以移动到当前位置
				logger.trace("client eat first:"+parent.selectedChessManPanel.cm.getName()+" second:"+cm.getName());
				//send request 比较大小 服务端修改布局 判断输赢
				ChessPackage cp=new ChessPackage(CONSTS.CMD_SEC,dataService.getPlayerID());
				Request request = new Request();
				request.setCommand(CONSTS.CMD_SEC_EAT);
				
				request.setFrom(commonLayoutService.revertPosition(parent.selectedChessManPanel.cm.getPosition(),dataService.getPlayer().getSeatName()));
				request.setTo(commonLayoutService.revertPosition(cm.getPosition(),dataService.getPlayer().getSeatName()));
				
				byte[] serRequest = null;
				try {
					serRequest = SerialUtil.enSerial(request);
				} catch (IOException e1) {
					e1.printStackTrace();
					return ;
				}
				serRequest=Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
				cp.setContent(serRequest);
				
				parent.toChessManPanel=this;
				parent.parent.updateSysMessage("走棋。选中第二个棋子。等待回复");
				parent.selectedChessManPanel.jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
				//发送请求
				parent.parent.control.sendRequest(cp);
				
				parent.parent.endTimeCount();
			}else{
				return ;
			}
		}
		
	}

	public void mouseEntered(MouseEvent e) {
		jLabelChess.setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.WHITE, 2, true), null));
	}

	public void mouseExited(MouseEvent e) {
		if(parent.selectedChessManPanel!=null&&parent.selectedChessManPanel.cm.getPosition().equals(cm.getPosition())){
			jLabelChess.setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.GREEN, 2, true), null));
		}else{
			jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
		}
	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}
	
}
